/**
 * Project Name:九色鹿
 * File Name:NotifySmsProvider.java
 * Package Name:com.fxp.project.sms.chuanglan.provider
 * Date:2021年09月14日 11:00
 * Copyright (c) 2021, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.sms.chuanglan.provider;

import com.alibaba.fastjson.JSON;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.commons.http.HttpRestTools;
import com.fxp.project.sms.chuanglan.config.NotificationProperties;
import com.fxp.project.sms.chuanglan.entity.SmsReceive;
import com.fxp.project.sms.chuanglan.entity.SmsSend;
import lombok.extern.log4j.Log4j2;

/**
 * ClassName:NotifySmsProvider<br/>
 * Function: 通知短信真实注入<br/>
 * Date:2021年09月14日 11:00<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK 8
 */
@Log4j2
public class NotifySmsProvider {
    /**
     * 配置对象
     */
    private NotificationProperties properties;

    /**
     * NotifySmsProvider: 私有的构建方法<br/>
     *
     * @param properties
     * @author Jason.Wang
     * @date 2021/9/13 17:49
     */
    private NotifySmsProvider(NotificationProperties properties) {
        this.properties = properties;
    }

    /**
     * init: 初始化方法<br/>
     *
     * @param properties
     * @return
     * @author Jason.Wang
     * @date 2021/9/13 17:50
     */
    public NotifySmsProvider init(NotificationProperties properties) {
        this.properties = properties;
        return new NotifySmsProvider(properties);
    }

    /**
     * sendSms: 发送短信验证码<br/>
     *
     * @param mobile
     * @param message
     * @return
     * @throws JiuLuException
     * @author Jason.Wang
     * @date 2021/9/13 17:49
     */
    public boolean sendSms(String mobile, String message) throws JiuLuException {
        SmsSend smsSend = SmsSend.builder().account(properties.getAppId()).password(properties.getAppKey()).msg(message).phone(mobile).build();
        SmsReceive smsReceive = HttpRestTools.postForEntity(properties.getSmsUrl(), smsSend, SmsReceive.class);
        log.info("通知短信发送后获取内容为：{}", JSON.toJSONString(smsReceive));
        if (null != smsReceive && smsReceive.getCode() == 0) {
            return true;
        } else {
            log.info("send “{}” to “{}” failed.", message, mobile);
            assert smsReceive != null;
            throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(), smsReceive.getErrorMsg());
        }
    }
}